package com.trickytriads.viewmodels
{
	import com.trickytriads.events.GetAllGamesEvent;
	import com.trickytriads.events.LoadingEvent;
	import com.trickytriads.model.GameData;
	import com.trickytriads.viewmodels.interfaces.I_GamelistViewModel;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;

	/**
	 * Viewmodel for the GamelistView.
	 */
	[AsyncInit]
	[Event(name="getAllGamesRequest",type="com.trickytriads.events.GetAllGamesEvent")]
	[Event(name="loadGeneric",type="com.trickytriads.events.LoadingEvent")]
	[ManagedEvents("getAllGamesRequest, loadGeneric")]
	public class GamelistViewModel extends EventDispatcher implements I_GamelistViewModel
	{		
		private var _currentGameList:ArrayCollection;
		
		public function GamelistViewModel()
		{
		}

		// Gets the games of the current player.  Call upon load.
		[PostConstruct]
		public function getGamesOfCurrentPlayer () : void
		{
			trace("Getting the games of the current player.");
			// For now, just assume that the player id is mine
			var player_id:Number = 15206400;
			dispatchEvent(new GetAllGamesEvent(GetAllGamesEvent.GETALLGAMES_REQUEST, player_id));
			// Let parsley know we're good to go
			dispatchEvent(new Event(Event.COMPLETE));
		}

		/**
		 * Message handler for when the GetAllGamesEvent is finished.
		 */
		[MessageHandler(selector="getAllGamesDone")]
		public function getAllGamesDoneHandler(evt:GetAllGamesEvent) : void
		{
			trace("Adding games to the game list");
			// If the evt._gameList variable isn't null, set it to be the displayed game list.
			if (evt._gameList != null)
			{				
				var gameListCollection:ArrayCollection = new ArrayCollection(evt._gameList);
				this.displayedGameList = gameListCollection;
			}
			else
			{
				trace("Received null game list!!");
			}			
		}

		/**
		 * Temporary function that tests the displayedGameList bindings
		 */
		public function testBindingUpdate () : void
		{		
			var bindingArray:Array = new Array();
			var numItems:int = Math.ceil(Math.random() * 100) as int;
			for (var i:int = 0; i < numItems; i++)	
			{
				bindingArray.push(new GameData(i, 0, 0, null, null, null, 0, 0, 0));
			}
			displayedGameList = new ArrayCollection(bindingArray);
		}

		[Bindable]
		public function get displayedGameList():ArrayCollection
		{
			return _currentGameList;
		}
		
		public function set displayedGameList(v:ArrayCollection):void
		{
			// Unset
			_currentGameList = null;
			// Set & refresh
			_currentGameList = v;
			_currentGameList.refresh();
		}
		
	}
}